import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  serverRequest: ['token', 'city', 'longitude', 'latitude', 'filterType', 'filterSort'],
  serverSuccess: ['payload'],
  serverFailure: null
})

export const ServerTypes = Types
export default Creators

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
  city: null,
  longitude: null,
  latitude: null,
  filterType: null,
  filterSort: null,
  fetching: null,
  payload: null,
  error: null
})

/* ------------- Reducers ------------- */

// request the data from an api
export const request = (state, action) => {
  const { city, longitude, latitude, filterType, filterSort } = action
  return state.merge({ fetching: true, payload: null, city, longitude, latitude, filterType, filterSort })
  }

// successful api lookup
export const success = (state, action) => {
  const { payload } = action
  return state.merge({ fetching: false, error: null, payload })
}

// Something went wrong somewhere.
export const failure = state =>
  state.merge({ fetching: false, error: true, payload: null })

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.SERVER_REQUEST]: request,
  [Types.SERVER_SUCCESS]: success,
  [Types.SERVER_FAILURE]: failure
})
